package com.songqintuan.common.validator;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.log4j.Logger;

import com.songqintuan.common.constant.GlobalConstants;
import com.songqintuan.common.util.MessageFactory;
import com.songqintuan.common.util.Validation;

@SuppressWarnings("serial")
public class ZipValidator implements Validator,Serializable {
	private static Logger logger = Logger.getLogger(Validation.class);
	 /**
	  * 正则验证方法
	  *
	  * @param regexstr
	  * @param str
	  * @return
	  */
	 public static boolean Match(String regexstr, String str) {
	  Pattern regex = Pattern.compile(regexstr,Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
	  Matcher matcher = regex.matcher(str);
	  return matcher.matches();
	 }

	
	public void validate(FacesContext context, UIComponent component, Object obj)
			throws ValidatorException {
		// TODO Auto-generated method stub
		String zipcoderegex = "^[0-9]{6}$";
		
		String zipCode=(String)obj;
		FacesMessage message;
		String label = (String)component.getAttributes().get("label");
		label = (null == label)?"":label;
		boolean matchFlag = Match(zipcoderegex, zipCode);
		if (!matchFlag)
	 	{
			message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "zip.validator.error.message", FacesMessage.SEVERITY_ERROR, label);
	 		throw new ValidatorException(message);
	    }
	}

}

